/**
 * 微信唤醒快速修复工具
 * 提供一键修复常见微信唤醒问题的功能
 */

import wechatAuth from @/utils/wechat'

/**
 * 修复类型枚举
 */
export const FIX_TYPES = {
  ENVIRONMENT: 'environment',
  CONFIGURATION: 'configuration',
  PERMISSION: 'permission',
  NETWORK: 'network',
  API: 'api'
}

/**
 * 修复结果类
 */
class FixResult {
  constructor(type, success, message, details = {}) {
    this.type = type
    this.success = success
    this.message = message
    this.details = details
    this.timestamp = Date.now()
  }
}

/**
 * 微信唤醒快速修复器
 */
class WechatQuickFixer {
  constructor() {
    this.fixResults = []
  }

  /**
   * 执行快速修复
   */
  async runQuickFix() {
    console.log('开始微信唤醒快速修复...')
    
    this.fixResults = []
    
    // 1. 环境修复
    await this.fixEnvironment()
    
    // 2. 配置修复
    await this.fixConfiguration()
    
    // 3. 权限修复
    await this.fixPermission()
    
    // 4. 网络修复
    await this.fixNetwork()
    
    // 5. API修复
    await this.fixApi()
    
    console.log('微信唤醒快速修复完成:', this.fixResults)
    return this.getFixSummary()
  }

  /**
   * 修复环境问题
   */
  async fixEnvironment() {
    const result = new FixResult(FIX_TYPES.ENVIRONMENT, false, '环境检查')
    
    try {
      const env = wechatAuth.checkEnvironment()
      
      if (env.isWechatMiniProgram) {
        result.success = true
        result.message = '小程序环境正常，无需修复'
        result.details = { environment: 'miniProgram' }
      } else if (env.isApp) {
        result.success = true
        result.message = 'APP环境正常，无需修复'
        result.details = { environment: 'app' }
      } else if (env.isWechatBrowser) {
        result.success = true
        result.message = '微信浏览器环境正常，无需修复'
        result.details = { environment: 'wechatBrowser' }
      } else {
        result.message = '当前环境不支持微信唤醒，建议在微信小程序、APP或微信浏览器中使用'
        result.details = { 
          environment: 'unsupported',
          suggestion: '请在支持的环境中重新尝试'
        }
      }
    } catch (error) {
      result.message = `环境检查失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.fixResults.push(result)
  }

  /**
   * 修复配置问题
   */
  async fixConfiguration() {
    const result = new FixResult(FIX_TYPES.CONFIGURATION, false, '配置检查')
    
    try {
      const env = wechatAuth.checkEnvironment()
      
      if (env.isWechatMiniProgram) {
        // 检查小程序配置
        const appId = this.getMiniProgramAppId()
        if (appId && appId !== 'unknown') {
          result.success = true
          result.message = '小程序配置正常'
          result.details = { appId }
        } else {
          result.message = '小程序AppID未配置，请在manifest.json中配置正确的AppID'
          result.details = { 
            issue: 'missing_appid',
            solution: '在manifest.json的mp-weixin.appid中配置正确的小程序AppID'
          }
        }
      } else if (env.isApp) {
        // 检查APP配置
        result.success = true
        result.message = 'APP配置检查通过（需要手动验证manifest.json中的微信配置）'
        result.details = {
          suggestion: '请确保manifest.json中已正确配置微信登录服务'
        }
      } else {
        result.success = true
        result.message = '当前环境无需特殊配置'
      }
    } catch (error) {
      result.message = `配置检查失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.fixResults.push(result)
  }

  /**
   * 修复权限问题
   */
  async fixPermission() {
    const result = new FixResult(FIX_TYPES.PERMISSION, false, '权限检查')
    
    try {
      const env = wechatAuth.checkEnvironment()
      
      if (env.isWechatMiniProgram) {
        // 检查小程序权限
        const authSetting = await this.getMiniProgramAuthSetting()
        if (authSetting['scope.userInfo']) {
          result.success = true
          result.message = '用户信息权限已授权'
          result.details = { authorized: true }
        } else {
          result.message = '用户信息权限未授权，需要用户主动授权'
          result.details = { 
            authorized: false,
            suggestion: '请引导用户点击授权按钮进行微信授权'
          }
        }
      } else if (env.isApp) {
        result.success = true
        result.message = 'APP环境权限在登录时检查'
        result.details = { note: '权限检查将在登录过程中进行' }
      } else if (env.isWechatBrowser) {
        result.success = true
        result.message = '微信浏览器环境权限在登录时检查'
        result.details = { note: '权限检查将在登录过程中进行' }
      } else {
        result.message = '无法检查权限状态'
      }
    } catch (error) {
      result.message = `权限检查失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.fixResults.push(result)
  }

  /**
   * 修复网络问题
   */
  async fixNetwork() {
    const result = new FixResult(FIX_TYPES.NETWORK, false, '网络检查')
    
    try {
      const networkType = await this.getNetworkType()
      
      if (networkType === 'none') {
        result.message = '网络连接不可用，请检查网络设置'
        result.details = { 
          networkType,
          suggestion: '请确保设备已连接到网络'
        }
      } else if (networkType === 'wifi' || networkType === '4g' || networkType === '5g') {
        result.success = true
        result.message = `网络连接正常 (${networkType})`
        result.details = { networkType }
      } else {
        result.success = true
        result.message = `网络连接可用 (${networkType})`
        result.details = { 
          networkType,
          note: '网络可能不够稳定，建议使用WiFi或4G/5G网络'
        }
      }
    } catch (error) {
      result.message = `网络检查失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.fixResults.push(result)
  }

  /**
   * 修复API问题
   */
  async fixApi() {
    const result = new FixResult(FIX_TYPES.API, false, 'API检查')
    
    try {
      const env = wechatAuth.checkEnvironment()
      
      if (env.isWechatMiniProgram) {
        // 检查小程序API
        if (typeof wx !== 'undefined') {
          const apiCheck = {
            wx: typeof wx,
            wxLogin: typeof wx.login,
            wxGetSetting: typeof wx.getSetting,
            wxGetUserInfo: typeof wx.getUserInfo
          }
          
          if (apiCheck.wxLogin === 'function' && apiCheck.wxGetSetting === 'function') {
            result.success = true
            result.message = '微信小程序API可用'
            result.details = apiCheck
          } else {
            result.message = '微信小程序API不完整，可能版本过低'
            result.details = { 
              apiCheck,
              suggestion: '请更新微信到最新版本'
            }
          }
        } else {
          result.message = '微信小程序API不可用'
          result.details = { 
            issue: 'wx_undefined',
            suggestion: '请确保在微信小程序环境中运行'
          }
        }
      } else if (env.isApp) {
        // 检查APP API
        if (typeof plus !== 'undefined') {
          if (typeof plus.oauth !== 'undefined') {
            result.success = true
            result.message = 'HTML5+ OAuth API可用'
            result.details = {
              plus: typeof plus,
              plusOauth: typeof plus.oauth
            }
          } else {
            result.message = 'HTML5+ OAuth API不可用'
            result.details = { 
              issue: 'plus_oauth_undefined',
              suggestion: '请检查manifest.json中的OAuth配置'
            }
          }
        } else {
          result.message = 'HTML5+ API不可用'
          result.details = { 
            issue: 'plus_undefined',
            suggestion: '请确保在APP环境中运行'
          }
        }
      } else if (env.isWechatBrowser) {
        result.success = true
        result.message = '微信浏览器环境API正常'
      } else {
        result.message = '当前环境无可用API'
      }
    } catch (error) {
      result.message = `API检查失败: ${error.message}`
      result.details = { error: error.message }
    }
    
    this.fixResults.push(result)
  }

  /**
   * 获取小程序AppID
   */
  getMiniProgramAppId() {
    // #ifdef MP-WEIXIN
    return __wxConfig?.appId || 'unknown'
    // #endif
    return 'unknown'
  }

  /**
   * 获取小程序权限设置
   */
  async getMiniProgramAuthSetting() {
    return new Promise((resolve, reject) => {
      if (typeof wx === 'undefined') {
        reject(new Error('微信小程序API不可用'))
        return
      }
      
      wx.getSetting({
        success: (res) => {
          resolve(res.authSetting || {})
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
  }

  /**
   * 获取网络类型
   */
  async getNetworkType() {
    return new Promise((resolve) => {
      if (typeof uni !== 'undefined' && typeof uni.getNetworkType === 'function') {
        uni.getNetworkType({
          success: (res) => {
            resolve(res.networkType)
          },
          fail: () => {
            resolve('unknown')
          }
        })
      } else {
        resolve('unknown')
      }
    })
  }

  /**
   * 获取修复摘要
   */
  getFixSummary() {
    const summary = {
      total: this.fixResults.length,
      success: 0,
      failed: 0,
      issues: [],
      recommendations: []
    }
    
    this.fixResults.forEach(result => {
      if (result.success) {
        summary.success++
      } else {
        summary.failed++
        summary.issues.push({
          type: result.type,
          message: result.message,
          details: result.details
        })
      }
    })
    
    // 生成建议
    if (summary.failed > 0) {
      summary.recommendations.push('请解决上述问题后再尝试微信唤醒')
    }
    
    if (summary.success === summary.total) {
      summary.recommendations.push('所有检查项通过，可以正常使用微信唤醒功能')
    }
    
    return {
      summary,
      details: this.fixResults
    }
  }

  /**
   * 获取修复报告
   */
  getFixReport() {
    const fix = this.getFixSummary()
    
    let report = '微信唤醒快速修复报告\n'
    report += '=' * 50 + '\n\n'
    
    // 摘要
    report += `总检查项：${fix.summary.total}\n`
    report += `成功：${fix.summary.success}\n`
    report += `失败：${fix.summary.failed}\n\n`
    
    // 详细结果
    report += '详细结果：\n'
    fix.details.forEach((result, index) => {
      const statusIcon = result.success ? '✅' : '❌'
      
      report += `${index + 1}. ${statusIcon} ${result.message}\n`
      if (Object.keys(result.details).length > 0) {
        report += `   详情：${JSON.stringify(result.details)}\n`
      }
      report += '\n'
    })
    
    // 问题和建议
    if (fix.summary.issues.length > 0) {
      report += '发现的问题：\n'
      fix.summary.issues.forEach((issue, index) => {
        report += `${index + 1}. ${issue.message}\n`
        if (issue.details.suggestion) {
          report += `   建议：${issue.details.suggestion}\n`
        }
      })
      report += '\n'
    }
    
    if (fix.summary.recommendations.length > 0) {
      report += '建议：\n'
      fix.summary.recommendations.forEach((rec, index) => {
        report += `${index + 1}. ${rec}\n`
      })
    }
    
    return report
  }
}

// 创建单例实例
const wechatQuickFixer = new WechatQuickFixer()

// 导出函数
export const runQuickFix = () => wechatQuickFixer.runQuickFix()
export const getFixReport = () => wechatQuickFixer.getFixReport()
export const getFixResults = () => wechatQuickFixer.fixResults

export default wechatQuickFixer 